// 引入axios
import axios from 'axios';
// import store from '@/store'
import { useStore } from "@/store/piniaIndex"

let baseUrl = "http://localhost:8081/crm";
// 创建axios实例
const httpService = axios.create({
    // url前缀-'http:xxx.xxx'
    // baseURL: process.env.BASE_API, // 需自定义
    baseURL: baseUrl,
    // 请求超时时间
    timeout: 3000 // 需自定义
});

//添加请求和响应拦截器
// 添加请求拦截器
httpService.interceptors.request.use(function (config) {
    const tokenStore = useStore();
    // 在发送请求之前做些什么 GET_TOKEN
    config.headers.Authorization = tokenStore.GET_TOKEN()
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
httpService.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log('请求响应....', response);

    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

/*网络请求部分*/

/*
 *  get请求
 *  url:请求地址
 *  params:参数
 * */
export function get(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'get',
            params: params
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}


/*
 *  get带参数请求
 *  url:请求地址
 *  params:参数
 * */
export function getRestFulApi(url, pathParams = {}, queryParams = {}) {

    // 构建路径参数，例如替换 url 中的 {id} 或 {userId}
    let apiUrl = url;
    Object.keys(pathParams).forEach(key => {
        
        
        apiUrl = apiUrl.replace(`{${key}}`, pathParams[key]);
    });

    // 拼接查询参数
    const query = new URLSearchParams(queryParams).toString();
    if (query) {
        apiUrl += `?${query}`;
    }

    return new Promise((resolve, reject) => {
        httpService({
            url: apiUrl,
            method: 'get',
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}



/*
 *  post请求
 *  url:请求地址
 *  params:参数
 * */
export function post(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params
        }).then(response => {
            resolve(response);
        }).catch(error => {

            reject(error);
        });
    });
}



// 封装文件下载接口
export function downloadFile(url, params = {}) {
    return new Promise((resolve, reject) => {
        // 发起 GET 请求
        httpService({
            url: url,
            method: 'post',
            data: params,
            responseType: 'blob'  // 关键: 设置响应类型为 blob
        }).then(response => {
            // 文件下载成功后调用这个方法 Content-Disposition:
            const contentDisposition = response.headers['content-disposition'];
            const fileName = contentDisposition ? contentDisposition.split('filename=')[1] : 'downloaded-file';
            const blob = response.data;

            // 创建一个临时的 URL 来下载文件
            const link = document.createElement('a');
            const objectURL = URL.createObjectURL(blob);
            link.href = objectURL;
            link.download = fileName;  // 设置文件名
            link.click();

            // 释放创建的 objectURL
            URL.revokeObjectURL(objectURL);

            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}


/*
 *  文件上传
 *  url:请求地址
 *  params:参数
 * */
export function fileUpload(url, params = {}) {
    return new Promise((resolve, reject) => {
        httpService({
            url: url,
            method: 'post',
            data: params,
            headers: { 'Content-Type': 'multipart/form-data' }
        }).then(response => {
            resolve(response);
        }).catch(error => {
            reject(error);
        });
    });
}

export function getServerUrl() {
    return baseUrl;
}

export function getImageUrl() {
    return baseUrl + '/image/userAvatar/';
}

export default {
    get,
    post,
    fileUpload,
    getServerUrl,
    downloadFile,
    getRestFulApi
}
